package object

import (
	"io"
	"net/http"
	"ones-objects/config"
	"fmt"
)

type PutStream struct {
	writer *io.PipeWriter
	c chan error
}

func NewPutStream(server,name string) *PutStream {
	reader,writer := io.Pipe()
	c := make(chan error)

	go func() {
		req,_ := http.NewRequest("PUT", config.HTTP_PROTOCAL + server + config.OBJECTS_PATH + name, reader)
		client := http.Client{}

		res,err := client.Do(req)
		if err != nil && res.StatusCode != http.StatusOK {
			err = fmt.Errorf("dataserver return status is %s", res.StatusCode)
		}
		c <- err
	}()
	return &PutStream{writer,c}
}

func (put *PutStream) Write(p []byte) (int, error) {
	return put.writer.Write(p)
}
func (put *PutStream) Close() error {
	put.writer.Close()
	return <- put.c
}
